﻿using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using EasyComm.Base.Hosting;
using EasyComm.Hosting.Configuration;

namespace EasyComm.Base
{
    [DataContract]
    public class ServiceUnitBase<TContract> : IDisposable
        where TContract : class
    {
        private ServiceProxy<TContract> _proxy;

        [DataMember]
        public ServiceStatus Status { get; set; }

        [DataMember]
        public string Error { get; set; }

        [DataMember]
        public string Host { get; set; }

        [DataMember]
        public int Port { get; set; }

        [DataMember]
        public Uri ListenUri { get; set; }

        //[DataMember]
        //public virtual ServiceContractCollection Contracts { get; private set; }

        [DataMember]
        public int ProcessID { get; private set; }

        public ServiceProxy<TContract> Service
        {
            get { return GetProxy(); }
        }

        public ServiceUnitBase(EasyCommServiceHostBase serviceHost)
        {
            if (serviceHost != null)
            {
                ListenUri = serviceHost.ListenUri;
                if (ListenUri == null)
                {
                    ListenUri = serviceHost.Contracts[typeof(TContract)].ListenUri;
                }
                Host = serviceHost.BaseAddresses[0].DnsSafeHost;
                Port = serviceHost.BaseAddresses[0].Port;
            }
            ProcessID = Process.GetCurrentProcess().Id;
        }

        private ServiceProxy<TContract> GetProxy()
        {
            if (_proxy != null)
            {
                return _proxy;
            }
            Binding binding = GenericConfiguration.GetMainBinding();
            EndpointAddress address = new EndpointAddress(ListenUri);
            _proxy = new ServiceProxy<TContract>(binding, address);
            return _proxy;
        }

        public void Dispose()
        {
            if (_proxy != null)
            {
                _proxy.Dispose();
            }
        }
    }
}
